package com.sansecy.base;

import android.content.ContentResolver;
import android.content.ContentValues;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.provider.MediaStore;
import android.util.Log;

import androidx.annotation.RequiresApi;

import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;

public class MediaStoreUtil {

    public static final String APP_ENGLISH_NAME = "Caneratest";

    public static void mediaStoreInsertImage(ContentResolver contentResolver, String path, String name) {
        try {
            MediaStore.Images.Media.insertImage(contentResolver, path, name, null);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
    }

    public static ArrayList<String> queryImages(ContentResolver contentResolver) {
        ArrayList<String> images = new ArrayList<>();
        final String[] projection = {MediaStore.Images.Media.DATA};
        final Cursor cursor = contentResolver.query(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
                projection, null, null, null);
        if (cursor == null)
            return images;
        else if (cursor.getCount() > 0 && cursor.moveToFirst()) {
            do {
                String path = cursor.getString(cursor.getColumnIndex
                        (MediaStore.Files.FileColumns.DATA));
                images.add(path);
            } while (cursor.moveToNext());
        }
        cursor.close();
        return images;
    }

    //
//    private ArrayList<LayoutElementParcelable> listVideos() {
//        ArrayList<LayoutElementParcelable> videos = new ArrayList<>();
//        final String[] projection = {MediaStore.Images.Media.DATA};
//        final Cursor cursor = c.getContentResolver().query(MediaStore.Video.Media.EXTERNAL_CONTENT_URI,
//                projection, null, null, null);
//        if (cursor == null)
//            return videos;
//        else if (cursor.getCount() > 0 && cursor.moveToFirst()) {
//            do {
//                String path = cursor.getString(cursor.getColumnIndex
//                        (MediaStore.Files.FileColumns.DATA));
//                HybridFileParcelable strings = RootHelper.generateBaseFile(new File(path), showHiddenFiles);
//                if (strings != null) {
//                    LayoutElementParcelable parcelable = createListParcelables(strings);
//                    if(parcelable != null) videos.add(parcelable);
//                }
//            } while (cursor.moveToNext());
//        }
//        cursor.close();
//        return videos;
//    }
//
//    private ArrayList<LayoutElementParcelable> listaudio() {
//        String selection = MediaStore.Audio.Media.IS_MUSIC + " != 0";
//        String[] projection = {
//                MediaStore.Audio.Media.DATA
//        };
//
//        Cursor cursor = c.getContentResolver().query(
//                MediaStore.Audio.Media.EXTERNAL_CONTENT_URI,
//                projection,
//                selection,
//                null,
//                null);
//
//        ArrayList<LayoutElementParcelable> songs = new ArrayList<>();
//        if (cursor == null)
//            return songs;
//        else if (cursor.getCount() > 0 && cursor.moveToFirst()) {
//            do {
//                String path = cursor.getString(cursor.getColumnIndex
//                        (MediaStore.Files.FileColumns.DATA));
//                HybridFileParcelable strings = RootHelper.generateBaseFile(new File(path), showHiddenFiles);
//                if (strings != null) {
//                    LayoutElementParcelable parcelable = createListParcelables(strings);
//                    if(parcelable != null) songs.add(parcelable);
//                }
//            } while (cursor.moveToNext());
//        }
//        cursor.close();
//        return songs;
//    }
//
//    private ArrayList<LayoutElementParcelable> listDocs() {
//        ArrayList<LayoutElementParcelable> docs = new ArrayList<>();
//        final String[] projection = {MediaStore.Files.FileColumns.DATA};
//        Cursor cursor = c.getContentResolver().query(MediaStore.Files.getContentUri("external"),
//                projection, null, null, null);
//        String[] types = new String[]{".pdf", ".xml", ".html", ".asm", ".text/x-asm", ".def", ".in", ".rc",
//                ".list", ".log", ".pl", ".prop", ".properties", ".rc",
//                ".doc", ".docx", ".msg", ".odt", ".pages", ".rtf", ".txt", ".wpd", ".wps"};
//        if (cursor == null)
//            return docs;
//        else if (cursor.getCount() > 0 && cursor.moveToFirst()) {
//            do {
//                String path = cursor.getString(cursor.getColumnIndex
//                        (MediaStore.Files.FileColumns.DATA));
//                if (path != null && Arrays.asList(types).contains(path)) {
//                    HybridFileParcelable strings = RootHelper.generateBaseFile(new File(path), showHiddenFiles);
//                    if (strings != null) {
//                        LayoutElementParcelable parcelable = createListParcelables(strings);
//                        if(parcelable != null) docs.add(parcelable);
//                    }
//                }
//            } while (cursor.moveToNext());
//        }
//        cursor.close();
//        Collections.sort(docs, (lhs, rhs) -> -1 * Long.valueOf(lhs.date).compareTo(rhs.date));
//        if (docs.size() > 20)
//            for (int i = docs.size() - 1; i > 20; i--) {
//                docs.remove(i);
//            }
//        return docs;
//    }
//
//    private ArrayList<LayoutElementParcelable> listApks() {
//        ArrayList<LayoutElementParcelable> apks = new ArrayList<>();
//        final String[] projection = {MediaStore.Files.FileColumns.DATA};
//
//        Cursor cursor = c.getContentResolver()
//                .query(MediaStore.Files.getContentUri("external"), projection, null, null, null);
//        if (cursor == null)
//            return apks;
//        else if (cursor.getCount() > 0 && cursor.moveToFirst()) {
//            do {
//                String path = cursor.getString(cursor.getColumnIndex
//                        (MediaStore.Files.FileColumns.DATA));
//                if (path != null && path.endsWith(".apk")) {
//                    HybridFileParcelable strings = RootHelper.generateBaseFile(new File(path), showHiddenFiles);
//                    if (strings != null) {
//                        LayoutElementParcelable parcelable = createListParcelables(strings);
//                        if(parcelable != null) apks.add(parcelable);
//                    }
//                }
//            } while (cursor.moveToNext());
//        }
//        cursor.close();
//        return apks;
//    }
    private static final String TAG = "MediaStoreUtil-App";

    public static String saveImageToMediaStore(ContentResolver contentResolver, File file, String name) {
        ContentValues contentValues = new ContentValues();

        contentValues.put(MediaStore.Images.ImageColumns.RELATIVE_PATH, "DCIM/Camera/");
        contentValues.put(MediaStore.Images.ImageColumns.DISPLAY_NAME, name);
        contentValues.put(MediaStore.Images.ImageColumns.MIME_TYPE, "image/jpeg");
        //会向Pictures/whooo/目录创建name.jpg的文件
        Uri uri = contentResolver.insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, contentValues);
        if (uri == null) {
            return "";
        }
        //写入图片
        OutputStream out = null;
        try {
            out = contentResolver.openOutputStream(uri);
            FileInputStream fileInputStream = new FileInputStream(file);
            byte[] bytes = new byte[1024];
            while (fileInputStream.read(bytes) != -1) {
                out.write(bytes);
            }
        } catch (IOException e) {
            return "";
        } finally {
            try {
                if (out != null) {
                    out.flush();
                    out.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return Environment.getExternalStorageDirectory() + "/Pictures/" + APP_ENGLISH_NAME + "/" + name;
    }

    public static String saveBitmapByMediaStore(ContentResolver contentResolver, Bitmap bitmap, String name) {
        ContentValues contentValues = new ContentValues();
        contentValues.put(MediaStore.Images.ImageColumns.RELATIVE_PATH, "Pictures/" + APP_ENGLISH_NAME + "/");
        contentValues.put(MediaStore.Images.ImageColumns.DISPLAY_NAME, name);
        contentValues.put(MediaStore.Images.ImageColumns.MIME_TYPE, "image/jpeg");
        contentValues.put(MediaStore.Images.ImageColumns.WIDTH, bitmap.getWidth());
        contentValues.put(MediaStore.Images.ImageColumns.HEIGHT, bitmap.getHeight());
        //会向Pictures/whooo/目录创建name.jpg的文件
        Uri uri = contentResolver.insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, contentValues);
        if (uri == null) {
            return "";
        }
        //写入图片
        OutputStream out = null;
        try {
            out = contentResolver.openOutputStream(uri);
            bitmap.compress(Bitmap.CompressFormat.JPEG, 100, out);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } finally {
            try {
                if (out != null) {
                    out.flush();
                    out.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return Environment.getExternalStorageDirectory() + "/Pictures/" + "/" + APP_ENGLISH_NAME + "/" + name + ".jpg";
    }

    public static String saveFileByMediaStore(ContentResolver contentResolver, String name, String content) {
        ContentValues contentValues = new ContentValues();
        contentValues.put(MediaStore.Images.ImageColumns.RELATIVE_PATH, "Download/" + APP_ENGLISH_NAME);
        contentValues.put(MediaStore.Images.ImageColumns.DISPLAY_NAME, name);
        contentValues.put(MediaStore.Images.ImageColumns.MIME_TYPE, "text/plain");
        Uri uri = contentResolver.insert(MediaStore.Downloads.EXTERNAL_CONTENT_URI, contentValues);
        if (uri == null) {
            return "";
        }
        OutputStream out = null;
        InputStream in = null;
        try {
            out = contentResolver.openOutputStream(uri);
            byte[] src = content.getBytes(StandardCharsets.UTF_8);
            if (src.length > 1024) {
                in = new ByteArrayInputStream(src);
                byte[] bytes = new byte[1024];
                while (in.read(bytes) != -1) {
                    out.write(bytes);
                }
            } else {
                out.write(src);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (in != null) {
                    in.close();
                }
                if (out != null) {
                    out.flush();
                    out.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return Environment.getExternalStorageDirectory() + "/Download/whooo/" + name + ".txt";
    }
}
